package com.zhuqi.stream;

import com.zhuqi.stream.entity.User;
import org.junit.jupiter.api.Test;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author ZhuQi
 * @ClassName Faltmap
 * @Date 2022/10/19 15:44
 * @Version 1.0
 * @Description TODO
 */
public class FlatMap {
    private static List<String> strs = new ArrayList(){{
        add("1,2,3,4,5");
        add("6,7,8,9,0");
    }};

    public static void main(String[] args) {

        // map 返回的是 object
        // 输出 [1, 2, 3, 4, 5],[6, 7, 8, 9, 0]
        strs.stream().map(s -> s.split(",")).forEach(s -> System.out.println(Arrays.toString(s)));

        // flatMap 返回的是一个 stream
        // 输出 1, 2, 3, 4, 5,6, 7, 8, 9, 0
        strs.stream().flatMap(s -> {
            String[] split = s.split(",");
            return Stream.of(split);
        }).forEach(System.out::println);
    }

    /**
     * 测试内容: 收集 Collectors.joining(",")
     * 测试结果: zs,ls,ww
     */
    @Test
    public void test01() throws Exception {
        ArrayList<String> list = new ArrayList<String>(){{
            add("zs");
            add("ls");
            add("ww");
        }};

        String str = list.stream().collect(Collectors.joining(","));
        System.out.println(str);
    }

    /**
     * 指定类型收集
     * 测试内容: 收集 Collectors.toCollection(TreeSet::new)
     * 测试结果: [ls, ww, zs]
     */
    @Test
    public void test02() throws Exception {
        ArrayList<String> list = new ArrayList<String>(){{
            add("zs");
            add("ls");
            add("ww");
        }};

        TreeSet<String> treeSet = list.stream().collect(Collectors.toCollection(TreeSet::new));
        System.out.println(treeSet);
    }

    /**
     * 收集成 HashMap
     * 测试内容: 收集 Collectors.toMap(User::getName, User::getAge)
     * 测试结果: {sg=22, zq=33, zx=11}   hashmap
     */
    @Test
    public void test03() throws Exception {
        ArrayList<User> list = new ArrayList<User>(){{
            add(new User("zx","11"));
            add(new User("sg","22"));
            add(new User("zq","33"));
        }};

        Map<String, User> map = list.stream().collect(Collectors.toMap(User::getName,(u) -> u));
        System.out.println(map);
        // hashMap
        System.out.println("map.class:" + map.getClass().getSimpleName());
    }

    /**
     * 收集 并统计
     * 测试内容: 收集 Collectors.groupingBy(User::getName, Collectors.counting())
     * 测试结果: {sg=1, zq=3, zx=1}
     */
    @Test
    public void test04() throws Exception {
        ArrayList<User> list = new ArrayList<User>(){{
            add(new User("zx","11"));
            add(new User("sg","22"));
            add(new User("zq","33"));
            add(new User("zq","44"));
            add(new User("zq","55"));
        }};

        Map<String, Long> map = list.stream().collect(Collectors.groupingBy(User::getName, Collectors.counting()));
        System.out.println(map);

    }
}
